package filewriting;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import commonfunctions.Matrix;

/**
 * Creates the matrix of probabilities (really a two-dimensional array) 
 * from a list of Observations.
 * 
 * Really, "probability" is a misnomer; it hasn't been calculated formally, so "weight" would be a 
 * more accurate term, since it's a relatively arbitrary number that is assigned to an edge.
 * 
 * @author Trevor Terris
 *
 */

public class ProbabilityMatrixWriter 
{	
	public static final String PROB_GRAPH_NAME = "prob-graph.txt";
	
	/**
	 * Creates the two-dimensional array, assuming that the list of observations has already been parsed.
	 * 
	 * @param observationList
	 * @param dirName
	 * @return
	 */
	public static Thread startWriting(Matrix weights, String dirName)
	{
		Thread toReturn = new WritingThread(weights, dirName);
		toReturn.start();
		return toReturn;
	}
	
	private static class WritingThread extends Thread
	{
		private Matrix myWeights;
		private String myDirName;
		public WritingThread(Matrix weights, String dirName)
		{
			myWeights = weights;
			myDirName = dirName;
		}
		public void run()
		{
			try
			{
		        File f = new File(myDirName + "/" + PROB_GRAPH_NAME);
		
		        Writer output = null;
		        output = new BufferedWriter(new FileWriter(f));
		        output.flush();
		        int size = myWeights.length();
		        
		        output.write("Lines: " + size + "\n");
		        
		        for (int i = 0; i < size; i++)
		        {
		        	for (int j = 0; j < size; j++)
		        	{
		        		if (j > i)
		        		{
		        			double prob = myWeights.get(i, j);
		        			//Uses the user-created probability function.
		        			if (prob != 0.0)
		        				output.write(j + " " + Double.toString(prob) + " ");
		        		}
		        	}
		        	if (i != size - 1)
		        		output.write("\n");
		        }
		        output.close();
			}
			catch (IOException e)
			{
				System.out.println("Trouble writing to file.");
			}
		}
	}
}
